<?php

declare(strict_types=1);

namespace LnkAdmin\controller\dict;

use LnkAdmin\controller\traits\Crud;
use think\Request;
use LnkAdmin\controller\Backend;
use LnkAdmin\model\dict\DictDataModel;
use LnkAdmin\model\dict\DictTypeModel;
use think\Response;
use think\facade\Db;

class DictType extends Backend
{
    use Crud;
    protected function initialize()
    {
        $this->model = new DictTypeModel;
    }

    /**
     * 查看
     *
     * @return Response
     */
    public function index(Request $request): Response
    {
        if (!empty($request->param('page_size'))) {       // 使用分页
            $params = $request->only(['name'=>'','code'=>'']);
            $list = $this->model
            ->when($params['name'],function($query) use($params){
                $query->where('name','like',`%{$params['name']}%`);
            })
            ->when($params['code'],function($query) use($params){
                $query->where('code',$params['code']);
            })
            ->paginate($request->param('page_size\d', 10));
        } else {
            $list = $this->model->select();               // 查询全部
        }

        return success('获取成功', $list);
    }


    /**
     * 删除(支持批量)
     *
     * @param  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $pk = $this->model->getPk();

        $result = Db::transaction(function () use ($id, $pk) {
            $count = 0;
            foreach ($this->model->whereIn($pk, $id)->cursor() as $row) {
                $count += $row->delete();
            }
            // 删除类型下的全部字典数据
            DictDataModel::where('type_id',$id)->delete();
            return $count;
        });
        if ($result) {
            return success('删除成功', $result);
        }
        return error('删除失败');
    }


}
